package com.sgb.kjwl.view.ui.activity.transport;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;

import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.gson.JsonObject;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPayBiddingBinding;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.DriverInfo;
import com.sgb.kjwl.model.entity.self.GoodsSourceDetail;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.Constants;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.utils.TextViewUtils;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.activity.self.AddCarInfoActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.CargoCustomValueAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.GoodsTagAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.PayGoodsInfoAdapter;
import com.sgb.kjwl.view.widget.CarListPopWindow;
import com.sgb.kjwl.view.widget.MyItemDecoration;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.transport.PayBiddingViewModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.FlowLayoutManager;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: 熊丽
 * @date: 2021/8/27
 * @Description: 竞价-新接单  2.1.0新增（防止后期改动较大）
 */
public class PayBiddingOrderActivity extends AppActivity {

    public static final int REQUEST_CODE = 200;
    public static final int RESULT_CODE = 201;
    PayBiddingViewModel mViewModel;
    ActivityPayBiddingBinding mBinding;
    //是否是我的报价管理进入(区分报价成功页展示)
    private boolean mIsManager;
    //是否是车主报价/团队和企业
    private boolean isDriver;
    //车辆选择
    private final List<CarInfo> mCarList = new ArrayList<>();
    private OptionsPickerView<CarInfo> mCarPicker;
    //货源信息
    private List<String> mTagList;
    private GoodsTagAdapter mTagAdapter;
    //货源信息
    private List<SingleItemEntity> mGoodsList;
    private PayGoodsInfoAdapter mGoodsAdapter;
    //货车信息
    private List<SingleItemEntity> mCarInfoList;
    private PayGoodsInfoAdapter mCarInfoAdapter;
    //自定义字段列表
    private List<SingleItemEntity> mCustomList;
    private CargoCustomValueAdapter mCustomAdapter;
    //当前选中车辆下标，-1代表未选中
    private int mSelectedCarIndex = -1;
    //当前选中车辆
    private CarInfo mSelectedCar;

    private String offerNo;
    CarListPopWindow carListPopWindow;
    private ImageAdapter adapter;
    private String urlStrings = "";
    private List<File> fileList = new ArrayList<>();
    private List<String> urls = new ArrayList<>();
    private int currentImgIndex;
    private int pageState = 0;
    private String orderNo = "";
    private String infoPrice = "";
    private List<LocalMedia> selectList = new ArrayList<>();
    private String freight;
    private String userNo;
    private GoodsSourceDetail goodsSourceDetail;
    private Calendar selectedDate =Calendar.getInstance();
    /**
     * 跳转报价
     *
     * @param context   上下文
     * @param no        货源no
     * @param isManager 是否是我的报价管理进入
     */
    public static void start(Context context, String no, boolean isManager,boolean isDriver,String freight) {
        Intent intent = new Intent(context, PayBiddingOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        intent.putExtra(RouterKey.BOOLEAN, isManager);
        intent.putExtra(RouterKey.STRING, freight);
        intent.putExtra(RouterKey.OWNER, isDriver);
        context.startActivity(intent);
    }

    /**
     * 默认请求码为 200
     */
    public static void startForResult(Activity activity, String no, boolean isManager, boolean isDriver, String freight) {
        Intent intent = new Intent(activity, PayBiddingOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        intent.putExtra(RouterKey.BOOLEAN, isManager);
        intent.putExtra(RouterKey.OWNER, isDriver);
        intent.putExtra(RouterKey.STRING, freight);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }
    @Override
    protected void init() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_pay_bidding);
        mViewModel = new ViewModelProvider(this).get(PayBiddingViewModel.class);
        mBinding.setLifecycleOwner(this);
        mBinding.includeTitle.titleView.setText("接单确认");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());
        mBinding.tvCargoOrdersProtocol.setText(Html.fromHtml("确认提交即表示您已阅读并同意"
                + "<font color='#5792FD'>《经营帮货物运输协议》</font>所有内容"));
        initRecycler();
        initEvent();
        initData();

    }

    private void initRecycler() {
        //货源标签
        mTagList = new ArrayList<>();
        mTagAdapter = new GoodsTagAdapter(mTagList);
        mBinding.rvCargoOrdersTag.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersTag.setLayoutManager(new FlowLayoutManager());
        mBinding.rvCargoOrdersTag.addItemDecoration(new MyItemDecoration());
        mTagAdapter.bindToRecyclerView(mBinding.rvCargoOrdersTag);
        //货源信息
        mGoodsList = new ArrayList<>();
        mGoodsAdapter = new PayGoodsInfoAdapter(mGoodsList);
        mBinding.rvCargoOrdersGoods.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersGoods.setLayoutManager(new LinearLayoutManager(this));
        mGoodsAdapter.bindToRecyclerView(mBinding.rvCargoOrdersGoods);
        //货车信息
        mCarInfoList = new ArrayList<>();
        mCarInfoAdapter = new PayGoodsInfoAdapter(mCarInfoList);
        mBinding.rvCargoOrdersCar.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersCar.setLayoutManager(new LinearLayoutManager(this));
        mCarInfoAdapter.bindToRecyclerView(mBinding.rvCargoOrdersCar);
        //自定义字段列表
        mCustomList = new ArrayList<>();
        mCustomAdapter = new CargoCustomValueAdapter(mCustomList);
        mBinding.rvCargoOrdersField.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersField.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvCargoOrdersField);
        mCustomAdapter.bindToRecyclerView(mBinding.rvCargoOrdersField);
        adapter = new ImageAdapter(this, null, null, 3);
        mBinding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mBinding.recyclerView.setAdapter(adapter);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        mBinding.setOnClick(this);
        //自定义字段删除监听
        mCustomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mCustomList.remove(position);
                mCustomAdapter.notifyDataSetChanged();
                if(mCustomList.size()==0){
                    mBinding.rvCargoOrdersField.setVisibility(View.GONE);
                }
            }
        });
        //限制输入
        mBinding.etCargoOrdersFreight.setOnFocusChangeListener(new RangeFocusChangeListener(1, 50000));
        //数据变化监听回调
        //货源数据
        mViewModel.ldCargo.observe(this, this::goodsSourceInfoEntry);
        //司机信息
        mViewModel.ldDriverInfo.observe(this, this::driverInfoEntry);
        //车辆信息
        mViewModel.ldCar.observe(this, this::syncCarList);
        //位置信息
        mViewModel.ldLocation.observe(this, this::syncLocation);
        //支付信息
        mViewModel.ldTradeNo.observe(this, no -> {
            BiddingQuotationSuccessActivity.startForResult(this, mIsManager, no);
            offerNo = no;
        });
        //文件上传
        mViewModel.uploadImgSuccess.observe(this,this::uploadImgSuccess);
        carListPopWindow=new CarListPopWindow(this);
        carListPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int pos=(int)key1;
                carSelect(pos);
            }
        });
    }


    private void initData() {
        mIsManager = getIntent().getBooleanExtra(RouterKey.BOOLEAN, false);
        isDriver = getIntent().getBooleanExtra(RouterKey.OWNER,false);
        String no = getIntent().getStringExtra(RouterKey.NO);
        freight = getIntent().getStringExtra(RouterKey.STRING);
        mViewModel.submitData().setIsVoluntarily(2);
        mViewModel.getDetail(this, no,isDriver);
        mViewModel.getCurrentLocation(this);
        mViewModel.getCarInfo(this);
    }

    /**
     * 司机信息录入
     */
    private void driverInfoEntry(DriverInfo driverInfo) {
        // mBinding.rvCargoOrdersCar.setVisibility(View.VISIBLE);
        mViewModel.submitData().setContrcts(driverInfo.getName());
        mViewModel.submitData().setContrctsNumber(driverInfo.getTelphone());
        mViewModel.syncDriverInfo(mCarInfoList, driverInfo);
        mCarInfoAdapter.notifyDataSetChanged();
    }

    /**
     * 货源信息录入
     */
    private void goodsSourceInfoEntry(GoodsSourceDetail goodsSourceDetail) {
        this.goodsSourceDetail = goodsSourceDetail;
        //运费核算
        mBinding.tvCargoOrdersFreight.setText(String.format("运费单价：%s元/吨", NumberUtil.trim0(goodsSourceDetail.getFreight())));
        //刷新货源tag
        mViewModel.syncTag(mTagList, goodsSourceDetail);
        mTagAdapter.notifyDataSetChanged();
        //刷新货源数据
        mViewModel.syncGoodsInfo(mGoodsList, goodsSourceDetail);
        mGoodsAdapter.notifyDataSetChanged();
        mBinding.carShow.setVisibility(isDriver?View.VISIBLE:View.GONE);
        //装货时间
        long currentTime = DateUtils.getCustomizeDayMorning(0, System.currentTimeMillis()).getTime();
        long beginTime = goodsSourceDetail.getShipmentTime();
        //装货开始时间大于当前时间则填入数据
        if (beginTime < currentTime) {
            mBinding.tvArrivalTime.setText(DateUtils.getDate());
            mViewModel.submitData().setInTime(currentTime);
        }else {
            mBinding.tvArrivalTime.setText(DateUtils.timestampTo13DateNos(beginTime));
            mViewModel.submitData().setInTime(beginTime);
        }
        mViewModel.submitData().setFreight(goodsSourceDetail.getFreight());

    }

    /**
     * 同步定位信息
     */
    private void syncLocation(AMapAddressEntity entity) {
        if (entity == null) return;
        mBinding.tvCargoOrdersCarLocation.setText(String.format("%s%s%s",
                entity.getProvince(),
                entity.getCity(),
                entity.getDistrict()));
        mBinding.line1.setVisibility(View.VISIBLE);
        mBinding.etCargoOrdersAddress.setVisibility(View.VISIBLE);
        mBinding.etCargoOrdersAddress.setText(DefaultUtil.getString(entity.getSnippet()));
        //设置数据
        mViewModel.submitData().setLat(entity.getLatitude());
        mViewModel.submitData().setLng(entity.getLongitude());
        mViewModel.submitData().setProvinceName(entity.getProvince());
        mViewModel.submitData().setCityName(entity.getCity());
        mViewModel.submitData().setDistrictName(entity.getDistrict());
        mViewModel.submitData().setProvinceNo(entity.getProvinceNo());
        mViewModel.submitData().setCityNo(entity.getCityNo());
        mViewModel.submitData().setDistrictNo(entity.getDistrictNo());
        mViewModel.submitData().setDetailAddress(entity.getSnippet());
        mViewModel.submitData().setContrcts( SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, ""));
        mViewModel.submitData().setContrctsNumber( SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));

        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        mViewModel.submitData().setTeamNo(UserOperating.getInstance().isTeam()? companyNo :"");
        mViewModel.submitData().setCompanyNo(UserOperating.getInstance().isCompany()? companyNo :"");
        if (!TextUtils.isEmpty(mViewModel.submitData().getCompanyNo())) {
            mViewModel.submitData().setOfferType(1);
            mViewModel.submitData().setBiddingUnit(companyName);
        } else if (!TextUtils.isEmpty(mViewModel.submitData().getTeamNo())) {
            mViewModel.submitData().setBiddingUnit(companyName);
            mViewModel.submitData().setOfferType(2);
        }else if (!TextUtils.isEmpty(userNo)) {
            mViewModel.submitData().setOfferType(3);
        }
    }

    /**
     * 初始化车辆选择器
     */
    private void syncCarList(List<CarInfo> list) {
        mCarList.clear();
        if (list == null) return;
        mCarList.addAll(list);
        carListPopWindow.setData(list);
        //当只有一辆车时，填入默认值
        if (mSelectedCarIndex == -1) {

            if (mCarList.size() == 1) {
                carSelect(0);
            }
        } else {
            carSelect(mSelectedCarIndex);
        }
    }

    /**
     * 车辆选择
     */
    private void carSelect(int index) {
        if (mCarList.size() <= index)
            return;
        mSelectedCarIndex = index;
        mSelectedCar = mCarList.get(index);
        if (mSelectedCar == null)
            return;
        StringBuilder strBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(mSelectedCar.getCarNumber())) {
            strBuilder.append(mSelectedCar.getCarNumber());
        }
        if (!TextUtils.isEmpty(mSelectedCar.getCarLenName())) {
            strBuilder.append("/");
            strBuilder.append(mSelectedCar.getCarLenName());
        }
        if (!TextUtils.isEmpty(mSelectedCar.getCarTypeName())) {
            strBuilder.append("/");
            strBuilder.append(mSelectedCar.getCarTypeName());
        }
        if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(mSelectedCar.getWeight())) != 0) {
            strBuilder.append("/");
            strBuilder.append(NumberUtil.trim0(mSelectedCar.getWeight())).append("吨");
        }
        mBinding.tvCargoOrdersCar.setText(strBuilder.toString());
        mViewModel.submitData().setDriverNo(mSelectedCar.getNo());
        mViewModel.submitData().setCarNumber(mSelectedCar.getCarNumber());
        if (mSelectedCar.getIsComplete() == 1) {
            mViewModel.submitData().setCarLenNo(mSelectedCar.getCarLenNo());
            mViewModel.submitData().setCarTypeNo(mSelectedCar.getCarTypeNo());
        }
    }

    @Override
    public void onMultiClick(View v) {
        if (v == mBinding.tvCargoOrdersExpand) {
            if (mBinding.tvCargoOrdersExpand.isSelected()) {
                mBinding.rvCargoOrdersGoods.setVisibility(View.GONE);
                mBinding.tvCargoOrdersExpand.setText("展开更多");
                TextViewUtils.changeTextView(this, mBinding.tvCargoOrdersExpand, R.drawable.btn_shop_down, false);
            } else {
                mBinding.rvCargoOrdersGoods.setVisibility(View.VISIBLE);
                mBinding.tvCargoOrdersExpand.setText("收起更多");
                TextViewUtils.changeTextView(this, mBinding.tvCargoOrdersExpand, R.drawable.btn_shop_up, true);
            }
        } else if (v == mBinding.llCargoOrdersCar) {
            if (carListPopWindow != null&&mCarList.size()>0) {
                carListPopWindow.showDownPopwindow(mBinding.llCargoOrdersCar,true);
                carListPopWindow.backgroundAlpha(0.5f);
            } else {
                MToast.showToast(this, "暂无数据");
            }
        } else if (v == mBinding.llCargoOrdersCarLocation) {
            AMapDialog.launch(this);
        } else if (v == mBinding.tvCargoOrdersAdd) {
            addField();
        } else if (v == mBinding.tvCargoOrdersSubmit) {
            clearAllFocus();
            if (isDriver){
                //设置门牌号
                mViewModel.submitData().setDetailAddress(DefaultUtil.getString(mBinding.etCargoOrdersAddress.getText().toString()));
            }
            //设置备注
            mViewModel.submitData().setNote(DefaultUtil.getString(mBinding.etCargoQuotationMark.getText().toString()));
            quotation(this, mSelectedCar,isDriver);
        } else if (v == mBinding.tvCargoOrdersProtocol) {
            EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.TRANSPORT_URL));
            WebActivity.start(this);
        }else if (v==mBinding.tvArrivalTime){
            setInsuranceTime();
        }
    }
    private void setInsuranceTime(){
        if (mViewModel.submitData()!=null &&mViewModel.submitData().getInTime()!=null) {
            Date time = new Date((mViewModel.submitData().getInTime()));
            selectedDate.setTime(time);
        }
        TimePickerView timePickerinsurance = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            mBinding.tvArrivalTime.setText(format);
            mViewModel.submitData().setInTime(date.getTime());
        }).setType(new boolean[]{true, true, true, false, false, false}).setCancelText("取消").setSubCalSize(15)
                .setRangDate( Calendar.getInstance(),null)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .setTitleText("选择到场时间")
                .build();
        if (selectedDate!=null) {
            timePickerinsurance.setDate(selectedDate);
        }
        timePickerinsurance.show();
    }
    /**
     * 报价（条件判断）
     */
    public void quotation(Context context, CarInfo car,boolean isDriver) {
        if (isDriver){
            if (car == null) {
                new RoundDialog.Builder(context)
                        .title("提示")
                        .content("请先选择车辆")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (car.getIsComplete() == 0) {
                new RoundDialog.Builder(context)
                        .title("提示")
                        .content("请先完善" + car.getCarNumber() + "的车辆信息")
                        .cancel("暂不完善")
                        .confirm("确定")
                        .confirmCallback(view -> ActivityJump.jumpToActivity(context, AddCarInfoActivity.class, Pair.create("carNo", NumberUtil.convertToLong(car.getNo()))))
                        .show();
                return;
            }
            if (mViewModel.submitData().getLat()==null) {
                new RoundDialog.Builder(context)
                        .title("提示")
                        .content("请先选择车辆位置")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (TextUtils.isEmpty(mViewModel.submitData().getDetailAddress())) {
                new RoundDialog.Builder(context)
                        .title("提示")
                        .content("请先输入楼牌号")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (!TextUtils.isEmpty(userNo)) {
                mViewModel.submitData().setBiddingUnit(TextUtils.isEmpty(mSelectedCar.getCarNumber())?"":mSelectedCar.getCarNumber());
            }
        }
        if (TextUtils.isEmpty(mViewModel.submitData().getFreight())) {
            new RoundDialog.Builder(context)
                    .title("提示")
                    .content("请先填写运费单价")
                    .cancel("确定")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .show();
            return;
        }
        if (TextUtils.isEmpty(mBinding.tvArrivalTime.getText().toString())){
            new RoundDialog.Builder(context)
                    .title("提示")
                    .content("请先填写预计到场时间")
                    .cancel("确定")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .show();
            return;
        }
        long currentTime;
        if (mViewModel.submitData()!=null &&mViewModel.submitData().getInTime()!=null){
            currentTime = mViewModel.submitData().getInTime();
        }else {
            currentTime=DateUtils.getCustomizeDayMorning(0, System.currentTimeMillis()).getTime();
        }
        long endTime = goodsSourceDetail.getShipmentEndTime()==null?0:goodsSourceDetail.getShipmentEndTime();
//        if (goodsSourceDetail.getShipmentTime()!=null&&goodsSourceDetail.getShipmentEndTime()!=null) {
//            if (DateUtils.stampToDay5(currentTime).equals(DateUtils.stampToDay5(endTime))) {
//                mViewModel.submitData().setInTime(endTime);
//            } else {
//                if (endTime < currentTime) {
//                    new RoundDialog.Builder(context)
//                            .title("提示")
//                            .content("当前货源最后可装货时间为" + CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime()) + "，请重新选择预计到场时间")
//                            .cancel("确定")
//                            .singleBtn(true)
//                            .contentGravity(Gravity.CENTER)
//                            .show();
//                    return;
//                }
//            }
//        }
//        if (goodsSourceDetail.getShipmentTime()!=null&&goodsSourceDetail.getShipmentEndTime()==null){
//            //计算是否是同一天
//            String biddingEndTime = DateUtils.stampToDay5(goodsSourceDetail.getShipmentTime());
//            String endTimes = DateUtils.stampToDay5(currentTime);
//            boolean isSameDay = !TextUtils.isEmpty(endTimes) && endTimes.equals(biddingEndTime);
//            //判断是否是同一天，同一天忽略截止时间判断
//            if (!isSameDay && currentTime  >goodsSourceDetail.getShipmentTime()) {
//                new RoundDialog.Builder(context)
//                        .title("提示")
//                        .content("当前货源最后可装货时间为" + CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), 0) + "，请重新选择预计到场时间")
//                        .cancel("确定")
//                        .singleBtn(true)
//                        .contentGravity(Gravity.CENTER)
//                        .show();
//                return;
//            }
//
//        }

        //判断自定义字段是否正确
        if (!loadFieldData()) {
            return;
        }
        if (mBinding.cbCargoOrdersProtocol.isChecked()) {
            //上传图片
            sureStartTransport();
        }  else {
            MToast.showToast(this, "请先勾选运输协议");
        }
    }

    /**
     * 添加更多字段
     */
    private void addField() {
        if (mCustomList.size() >= 3) {
            MToast.showToast(this, "最多添加3个字段");
            return;
        }
        mCustomList.add(new SingleItemEntity());
        mCustomAdapter.notifyDataSetChanged();
        if(mBinding.rvCargoOrdersField.getVisibility()==View.GONE){
            mBinding.rvCargoOrdersField.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 加载自定义字段
     */
    private boolean loadFieldData() {
        if (mCustomList != null && !mCustomList.isEmpty()) {
            Set<String> fieldName = new HashSet<>();
            //判断是否填写了自定义字段
            for (SingleItemEntity entity : mCustomList) {
                if (!fieldName.contains(entity.getLeftString())) {
                    fieldName.add(entity.getLeftString());
                } else {
                    MToast.showToast(this, "请检查新增字段名称是否有重复");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getLeftString())) {
                    MToast.showToast(this, "请输入新增字段名称");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getRightString())) {
                    MToast.showToast(this,"请输入新增字段内容");
                    return false;
                }
            }
            JsonObject field = new JsonObject();
            for (SingleItemEntity diy : mCustomList) {
                field.addProperty(diy.getLeftString(), diy.getRightString());
            }
            //设置自定义字段
            mViewModel.submitData().setAddField(field.toString());
        } else {
            mViewModel.submitData().setAddField(null);
        }
        return true;
    }
    public void sureStartTransport() {
        boolean unSelectedFile = fileList.size() == 0 || adapter.getFileList() == null
                || adapter.getFileList().size() == 0;
        if (unSelectedFile) {
            //提交报价
            mViewModel.quotation(this);
            return;
        }
        urlStrings = "";
        currentImgIndex = 0;
        mViewModel.uploadMutiFileModels(this,adapter.getFileList());
    }
    public void uploadImgSuccess(String url) {
        dealUrlString(url);
        //uploadImgAndSureStartTransport();
    }

    private void dealUrlString(String url) {
        mViewModel.submitData().setAccessory(url);
        //提交报价
        mViewModel.quotation(this);
    }

    private void uploadImgAndSureStartTransport() {
        if (currentImgIndex < fileList.size()) {
            mViewModel.uploadMutiFileModels(this, adapter.getFileList());
        } else {
            //图片上传完成后的操作
//            sureStartTransportAndArrived();
            //  mViewModel.saveLocation(orderNo);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE) {
            if (data != null && !TextUtils.isEmpty(data.getStringExtra("no"))) {
                Intent intent = new Intent();
                intent.putExtra("no", data.getStringExtra("no"));
                setResult(RESULT_CODE, intent);
            } else {
                setResult(RESULT_CODE);
            }
            finish();
        } else if (resultCode == RESULT_OK) {
            AMapAddressEntity entity = AMapDialog.get(data);
            if (entity != null) {
                syncLocation(entity);
            }
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                // 图片、视频、音频选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT) {
            mSelectedCar.setIsComplete(1);
            mViewModel.getCarInfo(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
